//
//  YCWebViewController.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/10.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  浏览器webview

#import "YCWebViewController.h"
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
#import "YCCustomShareView.h"
#import "WXApi.h"
#import <JavaScriptCore/JavaScriptCore.h>

@interface YCWebViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>
{
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}
@property (nonatomic,readonly) NSURL *url;
@property (nonatomic,readonly) NSUInteger clickLinkCount;

@end

@implementation YCWebViewController
@synthesize webView = _webView;
@synthesize url = _url;

#pragma mark - 属性获取方法

- (UIWebView *)webView
{
    if(!_webView)
    {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _webView.scalesPageToFit = YES;
        _webView.backgroundColor = [UIColor yc_colorWithUInt:0xefeff4];
        _webView.mediaPlaybackRequiresUserAction = NO;
    }
    return _webView;
}

#pragma mark - 视图控制器生命周期

- (instancetype)initWithURLString:(NSString *)urlString
{
    if(self = [super init])
    {
        //@"http://192.168.0.12:18088/gmall/G/normal/p-info.jsp?entityId=999534597&fromuid=999879903"
        _url = [NSURL URLWithString:urlString];
    }
    return self;
}


- (void)dealloc
{
    self.webView.delegate = nil;
    if(self.webView.loading)
    {
        [self.webView stopLoading];
        [self.webView removeFromSuperview];
    }
    _webView = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _progressProxy = [[NJKWebViewProgress alloc] init];
    self.webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    CGFloat progressBarHeight = 2.f;
    
    CGRect barFrame = CGRectMake(0, 0, self.view.yc_width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _progressView.progressBarView.backgroundColor = [UIColor blackColor];
    
    [self yc_addBackBarButtonItemWithTarget:self action:@selector(didTouchUpInsideBackBarButtonItem:)];
    
    [self.view addSubview:self.webView];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    [self.webView loadRequest:request];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.view addSubview:_progressView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_progressView removeFromSuperview];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

#pragma mark - UIWebView delegate

- (void)didTouchUpInsideShareButtonItem:(UIBarButtonItem *)item
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    
    [array addObject:@{YCCustomShareItemImageKey:@"weChat",
                       YCCustomShareItemTitleKey:@"微信好友",
                       }];
    
    [array addObject:@{YCCustomShareItemImageKey:@"sns_icon_23",
                       YCCustomShareItemTitleKey:@"朋友圈",
                       }];
    
    NSString *url = self.webView.request.URL.absoluteString;
    
    YCCustomShareView *shareView = [[YCCustomShareView alloc] initWithItems:[array copy]];
    YCCustomShareViewSendBlock send = ^(YCCustomShareView *view, NSDictionary *item) {
        
        WXWebpageObject *obj = [WXWebpageObject object];
        obj.webpageUrl = url;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"一乘驾校";
        message.description = @"立即下载一乘驾校";
        message.mediaObject = obj;
        message.thumbData = UIImageJPEGRepresentation([UIImage imageNamed:@"share"],1.0);
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.text = @"";
        req.message = message;
        req.bText = NO;
        req.scene = item == array.lastObject ? WXSceneTimeline : WXSceneSession;
        [WXApi sendReq:req];
    };
    
    YCCustomShareViewCancelBlock cancel =^{
        
    };
    
    [shareView showWithSendBlock:send cancel:cancel];
}

- (void)didTouchUpInsideBackBarButtonItem:(UIBarButtonItem *)backItem
{
    if(self.webView.canGoBack && self.clickLinkCount > 0)
    {
        [self.webView goBack];
        _clickLinkCount--;
        
        UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭"
                                                                      style:UIBarButtonItemStylePlain
                                                                     target:self
                                                                     action:@selector(didTouchUpInsideCloseBarButtonItem:)];
        self.navigationItem.leftBarButtonItems = @[self.navigationItem.leftBarButtonItem,closeItem];
    }
    else
    {
        if(self.webView.loading)
        {
            [self.webView stopLoading];
        }
        
        [self.webView loadHTMLString:@"" baseURL:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didTouchUpInsideCloseBarButtonItem:(UIBarButtonItem *)closeItem
{
    if(self.webView.loading)
    {
        [self.webView stopLoading];
    }
    
    [self.webView loadHTMLString:@"" baseURL:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(UIWebViewNavigationTypeLinkClicked == navigationType)
    {
        _clickLinkCount++;
    }
    
    if([request.URL.absoluteString isEqualToString:@"http://202.104.110.176:8088/usersoft/softnews/down.html"])
    {
        [self yc_addRightBarButtonItemWithImageNamed:@"addPublicPraise" target:self action:@selector(didTouchUpInsideShareButtonItem:)];
    }
    else
    {
        self.navigationItem.rightBarButtonItem = nil;
    }
    
    if([request.URL.absoluteString hasPrefix:@"inmyapp://share.myapp.gmall88.com"])
    {//标题和分享回调
        [self shareFromWebPageWithRequest:request.URL.absoluteString];
        return NO;
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //    JSValue *dict = context[@"GSDK"];
    //
    //    dict[@"log"] = ^(NSDictionary *ps){
    //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:ps[@"test"] message:nil delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
    //        [alertView show];
    //    };
    //    [context evaluateScript:@"GSDK.version='1.0.1';GSDK.initFinishedCallBack();"];
    
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(webView && webView.window)
        {
            [webView stringByEvaluatingJavaScriptFromString:@"var imgs = document.getElementsByTagName('img');for(var i=0;i<imgs.length;i++){img = imgs[i];img.style.webkitUserSelect='none';img.style.webkitTouchCallout='none';}"];
        }
    });
    
}

-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}

- (void)shareFromWebPageWithRequest:(NSString *)reqURLString
{
    NSString *url = [reqURLString yc_paramOfName:@"url"];
    if(!url)
    {
        [SVProgressHUD showErrorWithStatus:@"缺少url参数"];
        return;
    }
    
//    NSString *userid = [[GOLoginUser loginUser] gmallOpenID];
    NSString *userid = @"23241";
//    NSString *phone = [GOLoginUser loginUser].userMobilePhone;
    NSString *phone = @"13113361111";
    if([NSURL URLWithString:url].query)
    {
        url = [url stringByAppendingFormat:@"&userId=%@&phone=%@",userid,phone];
    }
    else
    {
        url = [url stringByAppendingFormat:@"?userId=%@&phone=%@",userid,phone];
    }
    
    NSString *title = [reqURLString yc_paramOfName:@"title"];
    NSString *desc = [reqURLString yc_paramOfName:@"desc"];
    //NSString *imgurl = [reqURLString go_paramOfName:@"img"];
    
    NSMutableArray *array = [[NSMutableArray alloc]init];
    
    [array addObject:@{YCCustomShareItemImageKey:@"weChat",
                       YCCustomShareItemTitleKey:@"微信好友",
                       }];
    
    [array addObject:@{YCCustomShareItemImageKey:@"sns_icon_23",
                       YCCustomShareItemTitleKey:@"朋友圈",
                       }];
    
    YCCustomShareView *shareView = [[YCCustomShareView alloc] initWithItems:[array copy]];
    YCCustomShareViewSendBlock send = ^(YCCustomShareView *view, NSDictionary *item) {
        
        WXWebpageObject *obj = [WXWebpageObject object];
        obj.webpageUrl = url;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title?title:@"缺少分享标题";
        message.description = desc?desc:@"缺少分享描述";
        message.mediaObject = obj;
        message.thumbData = UIImageJPEGRepresentation([UIImage imageNamed:@"share"],1.0);
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.text = @"";
        req.message = message;
        req.bText = NO;
        req.scene = item == array.lastObject ? WXSceneTimeline : WXSceneSession;
        [WXApi sendReq:req];
    };
    
    YCCustomShareViewCancelBlock cancel =^{
        
    };
    
    [shareView showWithSendBlock:send cancel:cancel];
}


@end
